﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Runtime.InteropServices;
using SchoolManagementSystem.Forms;
using DevExpress.XtraGrid.Views.Grid;
namespace SchoolManagementSystem.Controls
{
    public partial class DetailUC : UserControl
    {
        public DetailUC()
        {
            InitializeComponent();
            ID = -1;
            commandBarUC1.cmdsave.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barsaveitem_Click);
            commandBarUC1.cmdnew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(baradditem_Click);
            commandBarUC1.cmdrefresh.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barrefreshitem_Click);
            commandBarUC1.cmdcopy.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barcopy_Click);
            commandBarUC1.cmdaudit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(audit_Click);
            SaveAble = false;
          
        }



        public string ErrorMess;
       
        protected bool _boundData;
        private frmMaster _master;
        public frmMaster Master
        {
            get
            { 
                return _master;
            }
            set
            {
                _master = value;
            }
        }
        public MasterMainUC MasterUC { get; set; }

    

        public string Code { get; set; }
        protected string _objectName;
        public object Type { get; set; }
        public string ObjectName
        {
            get
            {
                return _objectName;
            }
            set
            {
                _objectName = value;
                string context = "Chi tiết";
                groupControl1.Text = String.Format(context + " {0}", _objectName);
            }
        }
        public long ID { get; set; }
        public bool SaveAble
        {
            get
            {
                return commandBarUC1.cmdsave.Enabled;
            }
            set
            {
                commandBarUC1.cmdsave.Enabled = value;
            }
        }

        public string GetTitleContext()
        {
            return groupControl1.Text;
        }
        protected void SetupSecurity()
        {
            string tag = Code;
            var userrolecheck = frmMain.UserModuleRole.FirstOrDefault(c => c.Module.Equals(tag));
            var grouprolecheck = frmMain.GroupModuleRole.FirstOrDefault(c => c.Module.Equals(tag));

            if ((userrolecheck != null && userrolecheck.Role.Contains("C")) || (grouprolecheck != null && grouprolecheck.Role.Contains("C")))
            {
               
                commandBarUC1.cmdnew.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                commandBarUC1.cmdsave.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                commandBarUC1.cmdsave.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                commandBarUC1.cmdnew.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }
            if ((userrolecheck != null && userrolecheck.Role.Contains("U")) || (grouprolecheck != null && grouprolecheck.Role.Contains("U")))
            {
                commandBarUC1.cmdsave.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                commandBarUC1.cmdsave.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }

        }


        void ShowAudit()
        {
            frmAudit audit = new frmAudit(Code);
            audit.ShowDialog();
        }

        void audit_Click(object sender, EventArgs e)
        {
            ShowAudit();
        }


        void baradditem_Click(object sender, EventArgs e)
        {
           groupControl1.Text= GetTitleContext() + " *";
            DetailAdd();
        }


        void barsaveitem_Click(object sender, EventArgs e)
        {
            DetailSave();
            if(Master!=null)
            Master.lblstatus.Caption = "Saved";
        }
        void barrefreshitem_Click(object sender, EventArgs e)
        {
            if (Master != null && !Master.ReloadData(ID))
                Display();
         
        }
        void barcopy_Click(object sender, EventArgs e)
        {
            XtraMessageBox.Show(String.Format("Thông tin của {0} đã được sao chép, bạn hãy bổ sung các thông tin khác biệt", _objectName), "Sao chép", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ID = -1;
        }


        public void DetailAdd()
        {
            if (SaveAble)
            {
                System.Windows.Forms.DialogResult dlg =  DevExpress.XtraEditors.XtraMessageBox.Show(String.Format("Dữ liệu của {0} [{1}] đã thay đổi, bạn có muốn lưu lại", ObjectName, ""), String.Format("Lưu {0}", ObjectName), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (dlg == System.Windows.Forms.DialogResult.Yes)
                    DetailSave();
                else if (dlg == System.Windows.Forms.DialogResult.Cancel)
                {
                    return;
                }
            }
          
            ID = -1;
            Display();
        }
        public long Display()
        {
            SetupSecurity();
            _boundData = false;
            SaveAble = false;
            long rt = DetailDisplay();
            _boundData = true;
            return rt;
        }

        public void DetailSave()
        {

            long oldID = ID;
            long NewID = -1;    
            NewID = Save();
            
            if (NewID < 0 && !String.IsNullOrEmpty(ErrorMess))
            {
                MessageControl.ShowMessage(ErrorMess,"Lỗi nhập liệu", MessageControl.Icon.Warning);
                ErrorMess = null;
                ID = oldID;
            }
            else
            {
                ID = NewID;
                if (Master != null && !Master.ReloadData(ID))
                    Display();
                if (MasterUC != null)
                    MasterUC.ReloadData(ID);
            }
        }

        public void Reload()
        {
            if (Master != null && !Master.ReloadData(ID))
                Display();
            if (MasterUC != null)
                MasterUC.ReloadData(ID);
        }

        protected virtual long DetailDisplay()
        {
            return ID;
        }

        protected virtual long Save()
        {
            return ID;
        }

        public virtual long Create()
        {
            return ID;
        }

        public virtual bool Delete(long SelectedID)
        {
            return false;
        }

         void CheckKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {

            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        protected void TextChangeCatcher(object sender, EventArgs e)
        {
            if (_boundData)
                SaveAble = true;
        }
        protected void AddTextChanged(ControlCollection controls)
        {

            for (int i = 0; i < controls.Count; i++)
            {
                Type type = controls[i].GetType();

                if (type == typeof(DateEdit))
                {
                    ((DateEdit)controls[i]).EditValueChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(CheckEdit))
                {
                    ((CheckEdit)controls[i]).CheckedChanged += new EventHandler(TextChangeCatcher);
                }
                else if(type== typeof(TextBox)||type== typeof(TextEdit)||type== typeof(MemoEdit))
                {
                    controls[i].TextChanged += new EventHandler(TextChangeCatcher);
                    if (controls[i].Name == "txtphone" || controls[i].Name=="txtcmnd" || controls[i].Name=="txtdiscount"|| controls[i].Name == "txtindentifycard" || controls[i].Name == "txtamount" || controls[i].Name == "txtnumber")
                    {
                        controls[i].KeyPress += new KeyPressEventHandler(CheckKeyPress);
                    }
                }
                if (type == typeof(CheckEdit))
                {
                    ((CheckEdit)controls[i]).CheckedChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(LookUpEdit))
                {
                    ((LookUpEdit)controls[i]).EditValueChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(PictureEdit))
                {
                    ((PictureEdit)controls[i]).EditValueChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(RadioGroup))
                {
                    ((RadioGroup)controls[i]).EditValueChanged += new EventHandler(TextChangeCatcher);
                    ((RadioGroup)controls[i]).SelectedIndexChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(SpinEdit))
                {
                    SpinEdit spin = (SpinEdit)controls[i];
                    string mask = "{0:0,0.###} ";
                    ((SpinEdit)controls[i]).ValueChanged += new EventHandler(TextChangeCatcher);
                    switch (controls[i].Name)
                    {
                        case "spinEdit_price":
                            mask += "đ";
                            break;
                        case "spinEdit_priceUSD":
                            mask += "usd";
                            break;                     
                    }
                    if(controls[i].Name.Contains("spinEdit_Money"))
                    {
                        mask += "đ";
                    }
                    spin.Properties.DisplayFormat.FormatString = mask;
                    spin.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;

                    spin.Properties.Mask.EditMask = "c0";
                    spin.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                }
                if (type == typeof(ComboboxUC))
                {
                    ((ComboboxUC)controls[i]).combobox.EditValueChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(ComboBoxEdit))
                {
                    ((ComboBoxEdit)controls[i]).EditValueChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(ColorPickEdit))
                {
                    ((ColorPickEdit)controls[i]).EditValueChanged += new EventHandler(TextChangeCatcher);
                }
                if (type == typeof(ButtonEdit))
                {
                    ((ButtonEdit)controls[i]).EditValueChanged += new EventHandler(TextChangeCatcher);
                }
            }
        }

        public string SearchString { get; set; }

        private void commandBarUC1_Load(object sender, EventArgs e)
        {

        }

        private void DetailUC_KeyDown(object sender, KeyEventArgs e)
        {
           
        }

       


        #region RegisterKeyPress

        //----------------------------------------------
        // Define the PeekMessage API call
        //----------------------------------------------

        private struct MSG
        {
            public IntPtr hwnd;
            public int message;
            public IntPtr wParam;
            public IntPtr lParam;
            public int time;
            public int pt_x;
            public int pt_y;
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        private static extern bool PeekMessage([In, Out] ref MSG msg,
            HandleRef hwnd, int msgMin, int msgMax, int remove);

        //----------------------------------------------

        /// <span class="code-SummaryComment"><summary> </span>
        /// Trap any keypress before child controls get hold of them
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="m">Windows message</param></span>
        /// <span class="code-SummaryComment"><returns>True if the keypress is handled</returns></span>
        protected override bool ProcessKeyPreview(ref Message m)
        {
            const int WM_KEYDOWN = 0x100;
            const int WM_KEYUP = 0x101;
            const int WM_CHAR = 0x102;
            const int WM_SYSCHAR = 0x106;
            const int WM_SYSKEYDOWN = 0x104;
            const int WM_SYSKEYUP = 0x105;
            const int WM_IME_CHAR = 0x286;

            KeyEventArgs e = null;

            if ((m.Msg != WM_CHAR) && (m.Msg != WM_SYSCHAR) && (m.Msg != WM_IME_CHAR))
            {
                e = new KeyEventArgs(((Keys)((int)((long)m.WParam))) | ModifierKeys);
                if ((m.Msg == WM_KEYDOWN) || (m.Msg == WM_SYSKEYDOWN))
                {
                    TrappedKeyDown(e);
                }
                //else
                //{
                //    TrappedKeyUp(e);
                //}

                // Remove any WM_CHAR type messages if supresskeypress is true.
                if (e.SuppressKeyPress)
                {
                    this.RemovePendingMessages(WM_CHAR, WM_CHAR);
                    this.RemovePendingMessages(WM_SYSCHAR, WM_SYSCHAR);
                    this.RemovePendingMessages(WM_IME_CHAR, WM_IME_CHAR);
                }

                if (e.Handled)
                {
                    return e.Handled;
                }
            }
            return base.ProcessKeyPreview(ref m);
        }

        private void RemovePendingMessages(int msgMin, int msgMax)
        {
            if (!this.IsDisposed)
            {
                MSG msg = new MSG();
                IntPtr handle = this.Handle;
                while (PeekMessage(ref msg,
                new HandleRef(this, handle), msgMin, msgMax, 1))
                {
                }
            }
        }

        /// <span class="code-SummaryComment"><summary></span>
        /// This routine gets called if a keydown has been trapped 
        /// before a child control can get it.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="e"></param></span>
        private void TrappedKeyDown(KeyEventArgs e)
        {
            PressKey(e);
        }




        void PressKey(KeyEventArgs e)
        {
            if (e.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.N:
                        DetailAdd();
                        break;
                    case Keys.S:
                        DetailSave();
                        break;
                    //case Keys.Delete: _detailControl.Delete(SelectedID);
                    //    break;
                }
            }

            if (e.KeyCode == Keys.F5)
            {
                if (Master != null && !Master.ReloadData(ID))
                    Display();
            }
            else if (e.KeyCode == Keys.Delete)
                {
                    Delete(ID);
                    //  Delete();
                }
            else if (e.KeyCode == Keys.F11)
            {
                ShowAudit();
            }
        }


        #endregion

    }
}
